package com.adcc.ags.gms.core.util;

import com.google.common.base.Strings;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 通用工具类
 */
public final class CommonUtil {

    /**
     * 获取IP地址
     * @param url
     * @return
     */
    public static String getIP(String url){
        String ip = Strings.emptyToNull("");
        String regexString="\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
        Pattern p = Pattern.compile(regexString);
        Matcher m = p.matcher(url);
        boolean result = m.find();
        if (result) {
            ip = m.group();
        }
        return ip;
    }

    /**
     * 获取字符串
     * @param is
     * @return
     * @throws IOException
     */
    public static String getString(InputStream is) throws IOException {
        int intLength = -1;
        byte[] buffer = new byte[1024];
        StringBuilder sb = new StringBuilder();
        while ((intLength = is.read(buffer,0,buffer.length)) > -1){
            String strValue =  new String(buffer,0,intLength);
            sb.append(strValue);
        }
        if(is != null){
            is.close();
        }
        return sb.toString();
    }

    /**
     * 多级反向代理下,获取当前网络ip
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }


}
